package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.EvaluationDTO;
import com.example.entity.OrderEvaluation;
import com.example.entity.enums.EvaluationStatusEnum;
import com.example.mapper.OrderEvaluationMapper;
import com.example.service.OrderEvaluationService;
import com.example.vo.MyEvaluationVO;
import com.example.vo.Result;
import com.example.vo.ResultCode;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
* @author circle48
* @description 针对表【order_evaluation】的数据库操作Service实现
* @createDate 2024-05-17 21:43:31
*/
@Service
@Slf4j
public class OrderEvaluationServiceImpl extends ServiceImpl<OrderEvaluationMapper, OrderEvaluation>
    implements OrderEvaluationService{

    @Resource
    private OrderEvaluationMapper orderEvaluationMapper;
    @Override
    public Result<IPage<MyEvaluationVO>> queryMineEvaluation(Integer pageNum, Integer pageSize, Long id, String evaluationStatus) {
        // 将枚举名称转换为对应的数字
        Integer status = null;
        if (evaluationStatus != null) {
            status = EvaluationStatusEnum.valueOf(evaluationStatus).ordinal();
        }
        Page<MyEvaluationVO> page = new Page<>(pageNum, pageSize);

        IPage<MyEvaluationVO> myEvaluationPage = orderEvaluationMapper.queryMineEvaluation(page, id,status);
        return Result.ok(myEvaluationPage);
    }


    @Override
    public List<OrderEvaluation> getEvaluationsToAutoDefault() {
        LocalDateTime fifteenDaysAgo = LocalDateTime.now().minusDays(15);
        Date createTime = Date.from(fifteenDaysAgo.atZone(ZoneId.systemDefault()).toInstant());

        LambdaQueryWrapper<OrderEvaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderEvaluation::getStatus, EvaluationStatusEnum.UN_EVALUATED)
                .le(OrderEvaluation::getCreateTime, createTime);

        return orderEvaluationMapper.selectList(queryWrapper);
    }

    @Override
    public void defaultEvaluation(Long evaluationId) {
        LambdaUpdateWrapper<OrderEvaluation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OrderEvaluation::getStatus, EvaluationStatusEnum.UN_EVALUATED)
                .set(OrderEvaluation::getContent, "系统默认好评")
                .set(OrderEvaluation::getGrade, 5.0)
                .eq(OrderEvaluation::getId, evaluationId);

        orderEvaluationMapper.update(null, updateWrapper);
    }


    @Override
    public Result addEvaluation(EvaluationDTO dto) {

        // 根据 orderSn 和 orderItemId 查找现有的评价记录
        QueryWrapper<OrderEvaluation> queryWrapper = new QueryWrapper<OrderEvaluation>()
//                .eq("order_sn", dto.getOrderSn())
                .eq("order_item_id", dto.getOrderItemId());

        Long count = baseMapper.selectCount(queryWrapper);
        if (count > 1) {
            return Result.error(ResultCode.ALREADY_EVALUATED);
        } else if (count == 0) {
            return Result.error(ResultCode.EVALUATION_RECORD_NOT_FOUND);
        }

        OrderEvaluation existingEvaluation = baseMapper.selectOne(queryWrapper);


        // 更新评价信息
        existingEvaluation.setContent(dto.getContent());
        existingEvaluation.setGrade(dto.getGrade());
        existingEvaluation.setServiceScore(dto.getServiceScore());
        existingEvaluation.setDeliveryScore(dto.getDeliveryScore());
        existingEvaluation.setGoodScore(dto.getGoodScore());
        existingEvaluation.setRootId(dto.getRootId());

        // 计算评分和设置类型
        calculateGradeAndType(existingEvaluation);

        // 检查是否上传了图片并设置 haveImage
        if (dto.getImages() == null || dto.getImages().trim().isEmpty()) {
            existingEvaluation.setHaveImage(false);
        } else {
            existingEvaluation.setHaveImage(true);
        }

        // 更新其他字段
        existingEvaluation.setUpdateTime(LocalDateTime.now());
        existingEvaluation.setDeleteFlag(false);
        existingEvaluation.setStatus(EvaluationStatusEnum.EVALUATED);
        // 更新已有评价
        baseMapper.updateById(existingEvaluation);

        return Result.ok("订单评价成功");
    }



    public void calculateGradeAndType(OrderEvaluation evaluation) {
        int deliveryScore = evaluation.getDeliveryScore();
        int serviceScore = evaluation.getServiceScore();
        int goodScore = evaluation.getGoodScore();

        // 计算总评分
        double grade = (deliveryScore * 0.2) + (serviceScore * 0.3) + (goodScore * 0.5);
        evaluation.setGrade(BigDecimal.valueOf(grade).setScale(1, BigDecimal.ROUND_HALF_UP));

        // 设置评价类型
        if (grade >= 4) {
            evaluation.setType(1); // 好评
        } else if (grade >= 2) {
            evaluation.setType(2); // 中评
        } else {
            evaluation.setType(3); // 差评
        }
    }


}




